[英]Take a string from user as a single command line argument, tokenize and display it
從用戶獲取一個字符串作為單個命令行參數。 標記化並將其存儲在適當的數據結構中,然后顯示它。
我嘗試了這段代碼,但它給了我分段錯誤。 我無法找到它在哪里。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define delim " "
int main(int argc, char *argv[])
{
if(argc!=2)
{
printf("\nPlease enter only one argument as a single line string.\n");
exit (-1);
}
char *tmp1=NULL;
int len=0;
int count=0;
int i=0;
len=strlen(argv[1]);
tmp1=(char *)malloc(sizeof(char)* (len)+1);
if(NULL==tmp1)
{
printf("Memory allocation failure single ptr.");
exit (-1);
}
strcpy(tmp1,argv[1]);
char *tok=NULL;
char **data=NULL;
tok=strtok(tmp1,delim);
while(NULL!=tok)
{
count++;
tok=strtok(NULL,delim);
}
strcpy(tmp1,argv[1]);
data=(char**)malloc(sizeof(char*)*count);
if(NULL==data)
{
printf("Memory allocation failure double ptr.");
exit (-1);
}
tok=strtok(tmp1,delim);
while (NULL!=tok)
{
int l=strlen(tok);
data[i]=(char *)malloc(sizeof(char)*l)+1);
if(NULL==data[i])
{
printf("Memory allocation failure ");
exit (-1);
}
strcpy(data[i],tok);
tok=strtok(NULL,delim);
i++;
}
for (i=0; i<count; i++)
{
printf("%s\t",data[i]);
}
for (i=0; i<count; i++)
{
free(data[i]);
data[i]=NULL;
}
data=NULL;
free(tmp1);
tmp1=NULL;
return 0;
}
我通過了“你好,這是字符串”,它導致分段錯誤。
據我從運行代碼中了解到的那樣,您想輸入一個字符串作為參數,然后解析並打印它,就這么簡單嗎?
由於輸入錯誤,代碼無法編譯:
data[i]=(char *)malloc(sizeof(char)*l)+1);
將其修復為:
data[i]=(char *)malloc(sizeof(char)*l+1);
代碼的輸出是,“您好,這是字符串”:
hello this is string
...Program finished with exit code 0
如果您仍然存在細分錯誤,請發布更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.